package com.my.oschina.fragment;

import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockListFragment;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.my.oschina.R;
import com.my.oschina.adapter.ListViewTweetAdapter;
import com.my.oschina.app.AppContext;
import com.my.oschina.app.AppException;
import com.my.oschina.bean.Result;
import com.my.oschina.bean.Tweet;
import com.my.oschina.bean.TweetList;
import com.my.oschina.common.UIHelper;

/**
 * 动弹-动弹的栏目，包括最新动弹、热门动弹、我的动弹
 * 
 * @说明 这个库的列表，没有单项长按事件
 * @author XuShaoJie
 * @version 2013-07-08
 */
public class TweetChildFragment extends SherlockListFragment {

	private int mInstance = -1;

	private PullToRefreshListView mPullRefreshListView;
	private ListViewTweetAdapter mNewsAdapter;
	private List<Tweet> lvNewsDataList = new ArrayList<Tweet>();
	private int lvSumData;// 加载的总数目

	private AppContext appContext;// 全局Context

	/**
	 * 返回FavoriteFragment实例
	 * 
	 * @param type
	 *            加载数据的类型
	 * @return FavoriteFragment实例
	 */
	public static TweetChildFragment newInstance(int type) {
		TweetChildFragment ff = new TweetChildFragment();
		Bundle bundle = new Bundle();
		bundle.putInt("type", type);
		ff.setArguments(bundle);
		return ff;
	}

	/**
	 * 
	 * @param type
	 * @param uid
	 * @return
	 */
	public static TweetChildFragment newInstance(int type, int uid) {
		TweetChildFragment ff = new TweetChildFragment();
		Bundle bundle = new Bundle();
		bundle.putInt("type", type);
		bundle.putInt("uid", uid);
		ff.setArguments(bundle);
		return ff;
	}

	private int getArgumentsType() {
		return getArguments().getInt("type", 0);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		appContext = (AppContext) getSherlockActivity().getApplication();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (savedInstanceState != null) {
			mInstance = savedInstanceState.getInt("mInstance");
		}
		View view = inflater.inflate(R.layout.activity_ptr_list, container,
				false);
		mPullRefreshListView = (PullToRefreshListView) view
				.findViewById(R.id.pull_refresh_list);
		mPullRefreshListView.setMode(Mode.BOTH);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		getListView().setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
		getListView().setOnItemLongClickListener(onItemLongClickListener);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		// Set a listener to be invoked when the list should be refreshed.
		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						String label = DateUtils.formatDateTime(appContext,
								System.currentTimeMillis(),
								DateUtils.FORMAT_SHOW_TIME
										| DateUtils.FORMAT_SHOW_DATE
										| DateUtils.FORMAT_ABBREV_ALL);

						// Update the LastUpdatedLabel
						refreshView.getLoadingLayoutProxy()
								.setLastUpdatedLabel(label);

						if (mPullRefreshListView.getCurrentMode() == Mode.PULL_FROM_START) {
							lvNewsDataList.clear();
							lvSumData = 0;
							mNewsAdapter.notifyDataSetChanged();
						}

						// 加载数据异步处理任务
						new GetFansTask().execute();
					}
				});

		mPullRefreshListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Tweet tweet = null;
				// 判断是否是TextView
				if (view instanceof TextView) {
					tweet = (Tweet) view.getTag();
				} else {
					TextView tv = (TextView) view
							.findViewById(R.id.tweet_listitem_username);
					tweet = (Tweet) tv.getTag();
				}
				if (tweet == null) {
					return;
				}
				// 跳转到动弹详情&评论页面
				UIHelper.showTweetDetail(view.getContext(), tweet.getId());
			}
		});

		// 注册上下文菜单
		// ListView actualListView = mPullRefreshListView.getRefreshableView();
		// registerForContextMenu(actualListView);

		mNewsAdapter = new ListViewTweetAdapter(getSherlockActivity(),
				lvNewsDataList, R.layout.tweet_listitem);
		mPullRefreshListView.setAdapter(mNewsAdapter);
		// actualListView.setAdapter(mNewsAdapter);

		// TODO 第一次启动时候加载数据
		new GetFansTask().execute();

	}

	/**
	 * 加载数据AsyncTask
	 */
	private class GetFansTask extends AsyncTask<String, Void, TweetList> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
					true);
		}

		@Override
		protected TweetList doInBackground(String... params) {
			// 当前pageIndex
			int pageIndex = lvSumData / 20;
			int type = getArgumentsType();
			try {
				return appContext.getTweetList(type, pageIndex, true);
			} catch (AppException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(TweetList result) {
			super.onPostExecute(result);

			// Call onRefreshComplete when the list has been refreshed.
			mPullRefreshListView.onRefreshComplete();

			List<Tweet> friendList = result.getTweetlist();
			// 加载成功且如果有数据
			if (result != null && friendList.size() > 0) {

				lvSumData += friendList.size();
				lvNewsDataList.addAll(result.getTweetlist());
				mNewsAdapter.notifyDataSetChanged();
				getSherlockActivity()
						.setSupportProgressBarIndeterminateVisibility(false);

				if (friendList.size() < 20) {
					mPullRefreshListView.setMode(Mode.PULL_FROM_START);
					// 添加监听器
					mPullRefreshListView
							.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
								@Override
								public void onLastItemVisible() {
									Toast.makeText(getSherlockActivity(),
											"已加载全部", Toast.LENGTH_SHORT).show();
								}
							});

				} else if (friendList.size() == 20) {
					mPullRefreshListView.setMode(Mode.BOTH);
					// 取消监听
					mPullRefreshListView.setOnLastItemVisibleListener(null);
				}
			}
			// 加载失败或者没有数据
			else {

			}
		}
	}

	private AdapterView.OnItemLongClickListener onItemLongClickListener = new AdapterView.OnItemLongClickListener() {

		@Override
		public boolean onItemLongClick(AdapterView<?> parent, View view,
				int position, long id) {
			Tweet _tweet = null;
			// 判断是否是TextView
			if (view instanceof TextView) {
				_tweet = (Tweet) view.getTag();
			} else {
				TextView tv = (TextView) view
						.findViewById(R.id.tweet_listitem_username);
				_tweet = (Tweet) tv.getTag();
			}
			if (_tweet == null) {
				return false;
			}
			final Tweet tweet = _tweet;
			// 删除操作
			final Handler handler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					if (msg.what == 1) {
						Result res = (Result) msg.obj;
						if (res.OK()) {
							lvNewsDataList.remove(tweet);
							mNewsAdapter.notifyDataSetChanged();
						}
						UIHelper.ToastMessage(getSherlockActivity(),
								res.getErrorMessage());
					} else {
						((AppException) msg.obj)
								.makeToast(getSherlockActivity());
					}
				}
			};
			Thread thread = new Thread() {
				@Override
				public void run() {
					Message msg = new Message();
					try {
						Result res = appContext.delTweet(
								appContext.getLoginUid(), tweet.getId());
						msg.what = 1;
						msg.obj = res;
					} catch (AppException e) {
						e.printStackTrace();
						msg.what = -1;
						msg.obj = e;
					}
					handler.sendMessage(msg);
				}
			};
			UIHelper.showTweetOptionDialog(getSherlockActivity(), thread);

			return true;
		}

	};

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("mInstance", mInstance);
	}

	// @Override
	// public void onCreateContextMenu(ContextMenu menu, View v,
	// ContextMenuInfo menuInfo) {
	// AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
	// menu.setHeaderTitle("Item: "
	// + getListView().getItemAtPosition(info.position));
	// menu.add("Item 1");
	// super.onCreateContextMenu(menu, v, menuInfo);
	// }

}
